<template>
	<s-layout title="铺货设置" navbar="normal1">
		<!-- 导航栏 -->
		<assNavbar title="铺货设置"></assNavbar>
		<!-- 内容 -->
		<view class="setting">
			<view class="form-box-top-header">
				<view class="title">请先完成批量铺货设置确认</view>
				<view class="desc">发货时效，售后服务和运费模板都可在铺货设置中调整或者编辑</view>
			</view>
			<view class="setting-form">
				<uni-forms ref="formRef" :modelValue="state.form" :rules="rules" label-width="120">
					<view class="form-box-content">

						<uni-forms-item label="鲸囍价" name="price_rate" required class="form-item">
							<view class="form-box-input-item form-box-input-item-price">
								<text class="font-2">采购价&nbsp;x&nbsp;(1+ </text>
								<input type="number" class="price1" v-model="state.form.price_rate" />
								<text>&nbsp;%)+</text>
								<input type="digit" maxlength="8" class="price2" v-model="state.form.money"  @input="inputChange" />
								<text>&nbsp;元</text>
							</view>
						</uni-forms-item>
						<uni-forms-item label="抹零方式" name="round_down" required>
							<view class="form-box-input-item">
								<!-- <radio-group disabled @change="changeRadio" class="ss-flex flex-wrap font-2">
									<label class="uni-list-cell uni-list-cell-pd ss-flex ss-m-l-10" v-for="(item, index) in radioList"
										:key="item.value">
										<radio color="#3662EC" style="transform: scale(0.6)" :value="item.value"
											:checked="state.form.round_down == item.value" />
										<view class="font-2" style="color:#202020">{{ item.label }}</view>
									</label>
								</radio-group> -->
								<view class="no-loose-change">
									<view class="item" v-for="(item, index) in radioList" :key="item.value" @tap="handleToggleChange(item)">
										<view class="title">{{ item.label }}</view>
										<view class="icon-box">
											<view :class="{'active': state.form.round_down === item.value, 'icon': state.form.round_down !== item.value  }"></view>
										</view>
									</view>
								</view>
							</view>
						</uni-forms-item>

						<uni-forms-item label="发货时效" name="delivery_time_type" required @tap="state.timelimitShow = true">
							<view class="form-box-input-item">
								<view style="font-size: 28rpx; flex: 1;">{{ timelimitRadioMap.find(item => item.value == state.form.delivery_time_type)?.name || '' }}</view>
								<uni-icons type="forward" size="18" color="#A6A6A6"></uni-icons>
							</view>
						</uni-forms-item>

						<uni-forms-item label="售后服务" name="aftersale" required @tap="state.salesServiceShow = true">
							<view class="form-box-input-item">
								<view style="font-size: 28rpx; flex: 1;">{{ salesServiceRadioMap.find(item => item.value == state.form.aftersale)?.name || '' }}</view>
								<uni-icons type="forward" size="18" color="#A6A6A6"></uni-icons>
							</view>
						</uni-forms-item>

						<uni-forms-item label="运费模板" name="dispatch_id" required @tap="state.freightShow = true">
							<view class="form-box-input-item">
								<view style="font-size: 28rpx; flex: 1;">{{ state.freightRadioMap.find(item => item.id == state.form.dispatch_id)?.name || '' }}</view>
								<uni-icons type="forward" size="18" color="#A6A6A6"></uni-icons>
							</view>
						</uni-forms-item>

						<uni-forms-item label="铺货状态" name="distribution" required>
							<view class="form-box-input-item">
								<!-- <radio-group disabled @change="changeDistributionStatusRadio"
									class="ss-flex flex-wrap font-2 ss-row-right">
									<label class="uni-list-cell uni-list-cell-pd ss-flex ss-m-l-10"
										v-for="(item, index) in distributionStatusList" :key="item.value">
										<radio color="#3662EC" style="transform: scale(0.6)" :value="item.value"
											:checked="state.form.distribution == item.value" />
										<view class="font-2" style="color:#202020">{{ item.label }}</view>
									</label>
								</radio-group> -->
								<view class="distribution-status">
									<view class="item" v-for="(item, index) in distributionStatusList" :key="item.value" @tap="handleToggleDistribution(item)">
										<view class="title">{{ item.label }}</view>
										<view class="icon-box">
											<view :class="{'active': state.form.distribution === item.value, 'icon': state.form.distribution !== item.value  }"></view>
										</view>
									</view>
								</view>
							</view>
						</uni-forms-item>

						<uni-forms-item label="限购地区" name="" required>
							<view class="form-box-input-item font-2">
								信息不同步（部分货源可能有地区限购）
							</view>
						</uni-forms-item>
						<uni-forms-item label="库存信息" name="" required>
							<view class="form-box-input-item font-2">
								不能单独维护库存，自动同步货源库存
							</view>
						</uni-forms-item>

					</view>
				</uni-forms>
			</view>
			<su-fixed bottom>
				<view class="bg-white ss-p-t-20 ss-p-b-20 ss-flex justify-center btns">
					<button class="btn ss-reset-button" @tap="handleCancel">
						取消
					</button>
					<button class="btn btn-save ss-reset-button " @tap="handleSubmit()">
						保存设置
					</button>
				</view>

			</su-fixed>
		</view>

		<!-- 发货时效 -->
		<su-popup :show="state.timelimitShow" round="25" @close="handlePopCancel('timelimitShow')">
			<view class="popupBox-title">发货时效</view>
			<view class="popupBox" >
				<view class="popupBox-item" v-for="(item, index) in timelimitRadioMap" :key="item.value"
					:class="{ 'active': state.form.delivery_time_type == item.value }" @tap="handleTimelimitSelected(item)">
					<view>{{ item.name }}</view>
					<view class="popupBox-item-img">
						<image :src="sheep.$url.cdn('/storage/default/20250418/e5963782138740e8e5931ac04a5b0ed3.png')"
							v-if="state.form.delivery_time_type == item.value"></image>
					</view>
				</view>
			</view>
		</su-popup>
		<!-- 服务保障 -->
		<su-popup :show="state.salesServiceShow" round="25" @close="handlePopCancel('salesServiceShow')">
			<view class="popupBox-title">服务保障</view>
			<view class="popupBox" >
				<view class="popupBox-item" v-for="(item, index) in salesServiceRadioMap" :key="item.value"
					:class="{ 'active': state.form.aftersale == item.value }" @tap="handleAftersalSelected(item)">
					<view>{{ item.name }}</view>
					<view class="popupBox-item-img">
						<image :src="sheep.$url.cdn('/storage/default/20250418/e5963782138740e8e5931ac04a5b0ed3.png')"
							v-if="state.form.aftersale == item.value"></image>
					</view>
				</view>
			</view>
		</su-popup>
		<!-- 运费模板 -->
		<su-popup :show="state.freightShow" round="25" @close="handlePopCancel('freightShow')">
			<view class="popupBox-title">运费模板</view>
			<view class="popupBox" >
				<scroll-view class="popupBox-scroll" scroll-y>
					<view class="popupBox-item" v-for="(item, index) in state.freightRadioMap" :key="item.id"
						:class="{ 'active': state.form.dispatch_id == item.id }" @tap="handleFreightSelected(item)">
						<view>{{ item.name }}</view>
						<view class="popupBox-item-img">
							<image :src="sheep.$url.cdn('/storage/default/20250418/e5963782138740e8e5931ac04a5b0ed3.png')"
								v-if="state.form.dispatch_id == item.id"></image>
						</view>
					</view>
				</scroll-view>
				
			</view>
		</su-popup>

	</s-layout>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue'
import { onLoad, onShow, onHide } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import assNavbar from '@/components/ass-navbar.vue';
import  { clone } from 'lodash'

const radioList = [
	{ value: 'keep_origin', label: '保留分角' },
	{ value: 'keep_up', label: '向上取整元' },
]
const distributionStatusList = [
	{ value: 'up', label: '铺货成功直接上架' },
	// { value: 'wait_up', label: '铺货成功后到待售' },
]

const timelimitRadioMap = [
	{ name: '48小时发货', value: 'hour48' },
	{ name: '当日发货', value: 'today' },
	{ name: '24小时发货', value: 'hour24' },
	{ name: '3天发货', value: 'day3' },
	{ name: '5天发货', value: 'day5' }
];
console.log(timelimitRadioMap['hour48'], 'uuuu')
const salesServiceRadioMap = [
	{ name: '支持7天无理由退换', value: 'day7', },
	{ name: '支持15天无理由退换', value: 'day15', },
	{ name: '支持30天无理由退换', value: 'day30', },
];


const formRef = ref(null);
const state = reactive({
	timelimitShow: false, // 发货时效
	salesServiceShow: false, // 服务保障
	freightShow: false, // 运费模板
	isAdd: true,

	form: {
		money: 30,
		price_rate: null,
		round_down: 'keep_origin',
		delivery_time_type: null,
		aftersale: null,
		dispatch_id: null,
		distribution: 'up',
		express_temp: '',
	},

	freightRadioMap: [] // 运费模版弹框list
})

const rules = {
	// 对name字段进行必填验证
	money: {
		rules: [
			{
				required: true,
				errorMessage: '请填写鲸囍价',
			},
		]
	},
	price_rate: {
		rules: [
			{
				required: true,
				errorMessage: '请填写鲸囍价',
			},
		]
	},
	round_down: {
		rules: [
			{
				required: true,
				errorMessage: '请选择抹零方式',
			},
		]
	},
	delivery_time_type: {
		rules: [
			{
				required: true,
				errorMessage: '请选择发货时效',
			},
		]
	},
	aftersale: {
		rules: [
			{
				required: true,
				errorMessage: '请选择售后服务',
			},
		]
	},
	dispatch_id: {
		rules: [
			{
				required: true,
				errorMessage: '请选择运费模板',
			},
		]
	},
	// 对name字段进行必填验证
	name: {
		rules: [
			{
				required: true,
				errorMessage: '请填写姓名',
			},
			{
				minLength: 1,
				maxLength: 6,
				errorMessage: '姓名长度在 {minLength} 到 {maxLength} 个字符',
			}
		]
	},

	round_down: { rules: [{ required: true, errorMessage: '请选择抹零方式' }] },

}

const handleToggleChange = item => {
	console.log(item)
	state.form.round_down = item.value
}
const handleToggleDistribution = item => {
	console.log(item)
	state.form.distribution = item.value
}

//输入时去除开头的0
const inputChange = (e) => {
	let value = e.detail.value;

  // 只允许数字和小数点
  value = value.replace(/[^\d.]/g, '');

  // 首位不能是小数点
  if (value.startsWith('.')) {
    value = '';
  }

  // 只允许出现一个小数点
  value = value.replace(/\.{2,}/g, '.'); // 连续点变一个
  value = value.replace('.', '#').replace(/\./g, '').replace('#', '.');

  // 首位是0，后面只能输入小数点
  if (value.startsWith('0') && value.length > 1) {
    if (value[1] !== '.') {
      value = '0';
    } else {
      // 小数点后只保留两位
      value = value.split('.')[0] + '.' + value.split('.')[1].slice(0, 2);
    }
  } else {
    // 小数点后只保留两位
    if (value.indexOf('.') > -1) {
      value = value.split('.')[0] + '.' + value.split('.')[1].slice(0, 2);
    }
  }

  nextTick(() => {
    state.form.money = value;
  });
}

// 发货时效
const handleTimelimitSelected = item => {
	console.log(item, 'item')
	state.form.delivery_time_type = item.value
	handlePopCancel('timelimitShow')
}
// 售后
const handleAftersalSelected = item => {
	console.log(item, 'item')
	state.form.aftersale = item.value
	handlePopCancel('salesServiceShow')
}

// 运费模板
const handleFreightSelected = item => {
	console.log(item, 'item')
	state.form.dispatch_id = item.id
	state.form.express_temp = item.name
	handlePopCancel('freightShow')
}
const handlePopCancel = (key) => {
	state[key] = false
}

const handleCancel = () => {
	uni.navigateBack()
}

const changeRadio = (e) => {
	console.log(e)
	state.form.round_down = e.detail.value
}
const changeDistributionStatusRadio = (e) => {
	console.log(e)
	state.form.distribution = e.detail.value
}

const handleSubmit = () => {
	console.log(11111, state.form)
	formRef.value.validate().then(async formVal => {
		console.log('formVal', formVal)
		const formSubmit = clone(state.form)
	
		// const res = state.edit ? await sheep.$api.commission.giveaway.writeEdit(state.form.id, {
		// 	...formSubmit,
		// 	status: 0
		// }) : await sheep.$api.commission.giveaway.write({
		// 	...formSubmit
		// })

		let resData = null
		if (state.isAdd) {
			resData = await sheep.$api.distribution.distributionAdd(state.form)
		} else {
			resData = await sheep.$api.distribution.distributionEdit(state.form)
		}

		console.log(resData, 'adddd & edit')

		if (resData.error == 0) {
			
			uni.showToast({
				title: '保存成功',
				icon: 'none',
				duration: 1000
			})

			sheep.$router.back()

		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none',
				duration: 2000
			})
		}
	}).catch(err => {
		console.log('err------', err);
	})
}

const getDispatchList = async () => {
	try {
		const { error, data, msg } = await sheep.$api.distribution.getDispatchList()
		console.log(data, 'data')
		if (error == 0) {
			state.freightRadioMap = data

		} else {
			uni.showToast({
			title: msg,
			icon: 'none',
		});
		}
	} catch (err) {
		uni.showToast({
			title: err,
			icon: 'none',
		});
	}

}

const getStoreDetail = async () => {
	try {
		const { error, data } = await sheep.$api.distribution.distributionDetail()
		console.log(error, 'error')
		console.log(data, 'data')
		// state.form = {}
		if (error == 0) {
			if (data) { // 有数据，为编辑状态
				state.isAdd = false

				console.log(data, '详情数据=')
				
				state.form = { ...state.form, ...data };
				if (data.price_rate) { // 采购价将数据转成整数
					const price_rate = parseInt(data.price_rate, 10);
					state.form = { ...state.form, ...{ price_rate } };
				}
				 
				console.log(state.form,'state.form')

			} else { // 无数据，是add
				state.isAdd = true
			}
		}
	} catch (error) {
		console.log(error)
	}
}

onLoad(async (opt) => {
	getStoreDetail()
	getDispatchList()
})

</script>

<style lang="scss" scoped>
@import './style/setting.scss';
</style>
